package cn.sczc.jh.client.controller;

import java.lang.reflect.Method;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;

import com.alibaba.fastjson.JSONObject;

import cn.sczc.jh.client.entity.User;
import cn.sczc.jh.client.exception.BusinessException;

//@Component
//@Aspect
public class ParamOutAspect {
	private final static Logger logger = LogManager.getLogger(ParamOutAspect.class);
	// 对包下所有的controller结尾的类的所有方法增强
	private final String executeExpr = "execution(* cn.sczc.jh.client..*Controller.*(..))";

	@Around(executeExpr)
	public Object doAroundAdvice(ProceedingJoinPoint joinPoint) {
		Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
		// 获取方法名称
		String methodName = method.getName();
//        //获取参数名称
//        LocalVariableTableParameterNameDiscoverer paramNames = new LocalVariableTableParameterNameDiscoverer();
//        String[] params = paramNames.getParameterNames(method);
		// 获取参数
		Object[] args = joinPoint.getArgs();
		logger.info("=============参数信息:{}", JSONObject.toJSONString(args));
		for (Object object : args) {
			if (object instanceof Model) {
				// 添加用户认证信息
				Subject subject = SecurityUtils.getSubject();
				User user = (User) subject.getPrincipal();
				((Model) object).addAttribute("permissionList", user.getPermissions());
			}
		}
		Object resObj = null;
		try {
			// 执行原方法
			resObj = joinPoint.proceed(args);
		} catch (Throwable e) {
			throw new BusinessException(methodName + "方法执行异常!");
		}
		return resObj;
	}

}
